package b0.controller;

import b0.bean.ResultInfo;
import b0.entity.Topic;
import b0.repository.TopicRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/topic")
public class TopicController {
    @Autowired
    TopicRepository topicRepository;

    @GetMapping("/{id}")
    public ResultInfo getTopic(@PathVariable("id") Integer id) {
        ResultInfo resultInfo = new ResultInfo();
        Topic topic = topicRepository.getOne(id);
        resultInfo.setData(topic);
        return resultInfo;
    }

    //增加
    @PostMapping("/add")
    public ResultInfo addTopic(Topic topic) {
        ResultInfo resultInfo = new ResultInfo();
        if (topic.getContent() != null){
            Topic save = topicRepository.save(topic);
            resultInfo.setStatus(200);
            resultInfo.setMsg("成功添加");
            resultInfo.setData(save);

        } else {
            resultInfo.setStatus(400);
            resultInfo.setMsg("添加失败");
            resultInfo.setData(topic);
        }
        return resultInfo;
    }

    //删除
    @DeleteMapping("/delete/{id}")
    public ResultInfo deleteTopic(@PathVariable("id")Integer id){
        ResultInfo resultInfo =new ResultInfo();
        topicRepository.deleteById(id);
        resultInfo.setStatus(200);
        resultInfo.setMsg("成功删除");
        return resultInfo;
    }


    @PutMapping("/update")
    public ResultInfo updateTopic(Topic topic){
        ResultInfo resultInfo = new ResultInfo();
        if (topic.getContent() != null){
            Topic save = topicRepository.save(topic);
            resultInfo.setStatus(200);
            resultInfo.setMsg("成功更新");
            resultInfo.setData(save);

        } else {
            resultInfo.setStatus(400);
            resultInfo.setMsg("更新失败");
            resultInfo.setData(topic);
        }
        return resultInfo;
    }
}
